package org.jetlinks.pro.network.manager.service;

import lombok.AllArgsConstructor;
import org.hswebframework.web.crud.events.EntityBeforeDeleteEvent;
import org.hswebframework.web.crud.events.EntityDeletedEvent;
import org.hswebframework.web.exception.BusinessException;
import org.jetlinks.pro.network.manager.entity.CertificateEntity;
import org.jetlinks.pro.network.manager.entity.DeviceGatewayEntity;
import org.jetlinks.pro.network.manager.entity.NetworkConfigEntity;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class NetworkEntityDeleteEventHandler {

    private final DeviceGatewayService gatewayService;

    private final NetworkConfigService networkService;

    //禁止删除已有网络组件使用的证书
    @EventListener
    public void handleCertificateDelete(EntityBeforeDeleteEvent<CertificateEntity> event) {
        event.async(
            Flux.fromIterable(event.getEntity())
                .flatMap(e->networkService
                    .createQuery()
                    // FIXME: 2021/9/13 由于网络组件没有直接记录证书，还有更好的处理办法？
                    .$like$(NetworkConfigEntity::getConfiguration,e.getId())
                    .or()
                    .$like$(NetworkConfigEntity::getCluster,e.getId())
                    .count()
                    .doOnNext(i -> {
                        if (i > 0) {
                            throw new BusinessException("error.certificate_has_bean_use_by_network");
                        }
                    })
                )
        );
    }

    //禁止删除已有网关使用的网络组件
    @EventListener
    public void handleNetworkDelete(EntityBeforeDeleteEvent<NetworkConfigEntity> event) {
        event.async(
            gatewayService
                .createQuery()
                .in(DeviceGatewayEntity::getNetworkId, event
                    .getEntity()
                    .stream()
                    .map(NetworkConfigEntity::getId)
                    .collect(Collectors.toList()))
                .count()
                .doOnNext(i -> {
                    if (i > 0) {
                        throw new BusinessException("error.network_has_bean_use_by_gateway");
                    }
                })
        );

    }

}
